#include	"Config.h"
#include	<utility>
#include	<algorithm>
#include	<exception>
#include	<fstream>
#include	<iostream>

Config::Config(int argc, char * argv[])
	:	m_application("")
	,	m_output("")
	,	m_input()
	,	m_logo(true)
	,	m_help(false)
	,	m_verbose(false)
	,	m_check(false)
{
	Parse(argc, argv);
}

Config::~Config()
{
}

const std::string & Config::Application() const
{
	return m_application;
}

const std::list< std::string > & Config::Input() const
{
	return m_input;
}

const std::string & Config::Output() const
{
	return m_output;
}

bool Config::Logo() const
{
	return m_logo;
}

bool Config::Help() const
{
	return m_help;
}

bool Config::Verbose() const
{
	return m_verbose;
}

bool Config::Check() const
{
	return m_check;
}

namespace
{

	std::pair< std::string, std::string > Split(const std::string & string)
	{
		std::pair< std::string, std::string > result("", "");
		std::string::size_type eq = string.find_first_of('=');
		std::string::size_type as = string.find_first_not_of("-/");
		if(as == 0)
		{
			result.second = string;
		}
		else if(eq == std::string::npos)
		{
			result.first = string.substr(as);
		}
		else
		{
			result.first = string.substr(as, eq - as);
			result.second = string.substr(eq + 1);
		}
		return result;
	}

}

void Config::Parse(int argc, char * argv[])
{
	m_application = argv[0];
	for(int i = 1; i < argc; ++i)
	{
		std::pair< std::string, std::string > param = Split(argv[i]);
		/* Debug
		std::cout << "argv[" << i << "] = \"" << argv[i] << "\"" << std::endl;
		std::cout << "    parsed as: \"" << param.first << "\" : \"" << param.second << "\"" << std::endl;
		// */
		if((param.first == "output") || (param.first == "out") || (param.first == "o"))
		{
			if(param.second == "")
			{
				throw std::exception("Error in command line - output expects a value");
			}
			m_output = param.second;
		}
		else if((param.first == "nologo") || (param.first == "l"))
		{
			m_logo = false;
		}
		else if((param.first == "help") || (param.first == "h") || (param.first == "?"))
		{
			m_help = true;
		}
		else if((param.first == "verbose") || (param.first == "v"))
		{
			m_verbose = true;
		}
		else if((param.first == "check") || (param.first == "c"))
		{
			m_check = true;
		}
		else if(param.first == "")
		{
			m_input.push_back(param.second);
		}
		else
		{
			throw std::exception("Error in command line - unknwon argument");
		}
	}
}

